﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.BusinessRule.CPR;
using Jumpton.SFA.Server.BusinessRule.CallRoute;

using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;

public partial class InStoreDataMeasures_CPRDataList : PageBase
{
    private const string NEW_PAGE = "Customer_Maintain.aspx";
    private OrgainzationManager orgManager = new OrgainzationManager();
    DataTable dt = null;
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            txt_datestart.Text = txt_dateend.Text = DateTime.Now.ToString("yyyy-MM-dd");
            DataBind();
            if (txtHidOrg.Value == "")
            {
                this.txtHidOrg.Value = OrgHidValue;
                this.txtOrg.Text = OrgShowValue;
                //OrgHelper.BindChiansDDL(MyStateManager.DomainID, this.txtHidOrg.Value, this.dd);

            }
            InitForm();


        }
    }

    #region 数据绑定
    private void InitForm()
    {



        drpCustomer.DataTextField = "Name";
        drpCustomer.DataValueField = "ID";
        drpCustomer.DataSource = CustomerManager.GetCustomers(MyStateManager.DomainID);
        //drpCustomer.DataSource = CustomerRouteManager.SelectUserCustomer(int.Parse(MyStateManager.UserID.ToString()), MyStateManager.DomainID, MyStateManager.OrgID);
        drpCustomer.DataBind();
        drpCustomer.Items.Insert(0, new ListItem("--全部--", ""));

    }
    #endregion



    #region 绑定查询数据
    public void BindGrid()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        if (drpCustomer.SelectedValue != "")
        {
            sb.Append(string.Format(" AND C.ID = {0} ", drpCustomer.SelectedValue));

        }



        dt = new CPRManager().GetCPRTable(MyStateManager.DomainID, decimal.Parse(DateTime.Parse(txt_datestart.Text).ToString("yyyyMMdd000000")), decimal.Parse(DateTime.Parse(txt_dateend.Text).ToString("yyyyMMdd999999")), sb.ToString());
        GridPager1.DataSource = dt;
        GridPager1.GridView = gvChannelType;
        GridPager1.BindData();
        GridPager1.Visible = gvChannelType.Rows.Count > 0;




    }
    #endregion

    //查询
    protected void btnQuery_Click(object sender, EventArgs e)
    {
        BindGrid();
    }

    protected void PageIndexChanged(object sender, GridViewPageEventArgs e)
    {
        gvChannelType.PageIndex = e.NewPageIndex;
        BindGrid();
    }

    public void GridViewToolbarUserControl1_OnGVTBSetColumnsButtonEvent(object sender, EventArgs e)
    {
        //gvChannelType.AllowPaging = false;
        BindGrid();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);
    }
    /// <summary>
    /// 分页
    /// </summary>
    public void GridViewPageIndexChanged()
    {
        BindGrid();
    }







    protected void gvChannelType_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //string query = "";
        //query += "?id=" + DataBinder.Eval(e.Row.DataItem, "ID");

        ////query += "&customer=" + txtCustomer.Text;
        ////query += "&channel=" + ddlChannel.SelectedValue;
        ////query += "&status=" + ddlStatus.SelectedValue;
        ////query += "&measure=" + ddlHasMeasures.SelectedValue;
        ////query += "&userlist=" + ddlUserList.SelectedValue;
        //query += "&valid=" + ddlValid.SelectedValue;
        //query += "&PageIndex=" + gvChannelType .PageIndex;

        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{
        //    HyperLink hl1 = (HyperLink)e.Row.FindControl("HyperLink1");
        //    HyperLink hl2 = (HyperLink)e.Row.FindControl("HyperLink2");
        //    if (hl1 != null)
        //    {
        //        hl1.NavigateUrl = "Customer_View.aspx" + query;
        //    }
        //    if (hl2 != null)
        //    {
        //        hl2.NavigateUrl = "Customer_View.aspx" + query;
        //    }
        //    e.Row.Cells[10].Text = DateTime.ParseExact(e.Row.Cells[10].Text, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture
        //             , System.Globalization.DateTimeStyles.None).ToString("yyyy年MM月dd日 HH:mm:ss");
        //}

    }


    protected void btnExport_Click(object sender, EventArgs e)
    {
        if (dt == null)
            dt = ViewState["dt"] as DataTable;
        DataTable2Excel(dt);
        //return;

        //System.IO.StringWriter tw = new System.IO.StringWriter();
        //System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        //foreach (Control cr in panelx.Controls)
        //{
        //    cr.RenderControl(hw);
        //}
        //string attachment = "attachment; filename=" + DateTime.Now.ToShortDateString() + ".xls";
        //HttpContext.Current.Response.ClearContent();
        //HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        //Response.Charset = "UTF-8";
        //Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");

        //Response.Write(tw.ToString());
        //Response.End();
    }


    public void DataTable2Excel(DataTable dtData)
    {

        if (dtData != null && dtData.Rows.Count > 0)
        {
            if (dtData.Columns.Count > 0)
            {
                dtData.Columns[0].ColumnName = "门店编号";
                dtData.Columns[1].ColumnName = "门店";
                dtData.Columns[2].ColumnName = "产品编号";
                dtData.Columns[3].ColumnName = "产品名称";
                dtData.Columns[4].ColumnName = "退货";
                dtData.Columns[5].ColumnName = "库存";
                dtData.Columns[6].ColumnName = "配货";
                dtData.Columns[7].ColumnName = "订单";
                dtData.Columns[8].ColumnName = "日期";
            }
        }
        else
        {
            ShowMessage("没有任何数据");
            return;
        }

      
       
        System.Web.HttpContext curContext = System.Web.HttpContext.Current;
        
      

        if (dtData != null)
        {
            // 设置编码和附件格式
            //curContext.Response.ContentType = "application/vnd.ms-excel";
            //curContext.Response.ContentEncoding =System.Text.Encoding.UTF8;
            //curContext.Response.Charset = "";
            //string attachment = "attachment; filename=" + DateTime.Now.ToShortDateString() + ".xls";
            //HttpContext.Current.Response.ClearContent();
            //HttpContext.Current.Response.AddHeader("content-disposition", attachment);
            //Response.Charset = "UTF-8";
            //Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            //// 导出excel文件
            //strWriter = new System.IO.StringWriter();
            //htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

            //// 为了解决dgData中可能进行了分页的情况，需要重新定义一个无分页的DataGrid
            //dgExport = new System.Web.UI.WebControls.DataGrid();
            //dgExport.DataSource = dtData.DefaultView;
            //dgExport.AllowPaging = false;
            //dgExport.DataBind();

            //// 返回客户端
            //dgExport.RenderControl(htmlWriter);
            //curContext.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=UTF-8\"/>" + strWriter.ToString());
            //curContext.Response.End();


            string filename = drpCustomer.SelectedIndex==0?DateTime.Now.ToString("yyyyMMddHHmmss"):DateTime.Now.ToString("yyyyMMddHHmmss")+drpCustomer.SelectedItem.Text;
            filename+=".xls";
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
            Response.Clear();

            InitializeWorkbook();
            GenerateData(filename, dtData);
            Response.BinaryWrite(WriteToStream().GetBuffer());
            Response.End();
        }
    }
    HSSFWorkbook hssfworkbook;

    MemoryStream WriteToStream()
    {
        //Write the stream data of workbook to the root directory
        MemoryStream file = new MemoryStream();
        hssfworkbook.Write(file);
        return file;
    }

    void GenerateData(string name,DataTable dt)
    {
        if (name == "")
            name = DateTime.Now.ToString("yyyyMMddHHmmss");
        ISheet sheet1 = hssfworkbook.CreateSheet(name);//创建工作簿
        sheet1.SetColumnWidth(0,25*256);//设置列宽
        sheet1.SetColumnWidth(1, 25 * 256);
        sheet1.SetColumnWidth(2, 15 * 256);
        sheet1.SetColumnWidth(3, 20 * 256);
        sheet1.SetColumnWidth(8, 10 * 256);
      
        sheet1.CreateFreezePane(1, 1);//冻结列头
        IRow row = sheet1.CreateRow(0);
        row.Height = 500;
        HSSFCellStyle cellStyle = (HSSFCellStyle)hssfworkbook.CreateCellStyle();//创建单元格样式
        HSSFDataFormat format = (HSSFDataFormat)hssfworkbook.CreateDataFormat();//创建显示格式
        HSSFFont font = (HSSFFont)hssfworkbook.CreateFont();//创建字体
        font.Boldweight = 4;
        font.FontHeight = 300;
        font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;//加粗
        font.FontHeight = 300;
        cellStyle.SetFont(font);

        cellStyle.Alignment = HorizontalAlignment.CENTER;//居中
        cellStyle.VerticalAlignment = VerticalAlignment.CENTER;
        cellStyle.SetFont(font);
        cellStyle.BorderTop = cellStyle.BorderBottom = cellStyle.BorderLeft = cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            ICell c = row.CreateCell(j);
            c.SetCellValue(dt.Columns[j].ColumnName);
            c.CellStyle = cellStyle;
            
        }
        cellStyle = (HSSFCellStyle)hssfworkbook.CreateCellStyle();//创建单元格样式
        cellStyle.BorderTop = cellStyle.BorderBottom = cellStyle.BorderLeft = cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;
        for (int i = 1; i < dt.Rows.Count; i++)
        {
            row = sheet1.CreateRow(i);
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                ICell c = row.CreateCell(j);
                c.SetCellValue(dt.Rows[i][j].ToString());
                c.CellStyle = cellStyle;
                
            }
        }
        
      
    }
   
    void InitializeWorkbook()
    {
        hssfworkbook = new HSSFWorkbook();

        ////create a entry of DocumentSummaryInformation
        DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
        dsi.Company = "AZYK";
        hssfworkbook.DocumentSummaryInformation = dsi;

        ////create a entry of SummaryInformation
        SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
        si.Subject = "AZYK";
        hssfworkbook.SummaryInformation = si;
    }



}
